package com.utils.wechat;

import com.bean.anno.BaseConfig;
import com.bean.sqlite.api.FreeApiJokes;
import com.bean.wechat.ResultInfo;
import com.mapper.repository.mysql.BaseConfigRepository;
import com.mapper.sqlite.FreeApiJokesMapper;
import com.service.FreeApiService;
import com.utils.BaseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WechatStrategyJokes implements WechatStrategy {

    @Autowired
    private BaseUtils baseUtils;

    @Autowired
    private FreeApiJokesMapper freeApiJokesMapper;

    @Autowired
    private FreeApiService freeApiService;

    @Autowired
    private BaseConfigRepository baseConfigRepository;

    @Override
    public void returnMsg(ResultInfo resultInfo, String content) {
        StringBuilder stringBuilder = new StringBuilder();
        //判断是否为公众号的拥有者，如果是，则调用接口，否则返回内容
        String owner = baseUtils.getBaseConfigByName("wechat_own");
        String toUserid = resultInfo.getToUserName();
        if(toUserid.equals(owner)){
            int page = 0;
            //判断是否有数据，如果没有则从0开始，否则从数据库的值开始
            if(freeApiJokesMapper.list().size()==0){
                page = 1;
            }else{
                page=Integer.parseInt(baseUtils.getBaseConfigByName("jokeApi_page"));
            }
            //调用Jokes的接口，获取数据
            String result = freeApiService.addJokes(page);
            if(result.startsWith("成功")){
                BaseConfig baseConfig =baseConfigRepository.getByName("jokeApi_page");
                baseConfig.setParam(page+1+"");
                baseConfigRepository.save(baseConfig);
            }else{
                stringBuilder.append(result+"\n");
            }
        }
        //返回一条数据
        FreeApiJokes freeApiJokes = freeApiJokesMapper.randomJokes();
        resultInfo.setReturnMethod("text");
        if(freeApiJokes!=null){
            //resultInfo.setContent(freeApiJokes.getContent());
            stringBuilder.append(freeApiJokes.getContent()+"\n");
        }else{
            stringBuilder.append("暂无内容"+"\n");
            //resultInfo.setContent("暂无内容");
        }
        resultInfo.setContent(stringBuilder.toString());
        resultInfo.setReturnMethod("text");
    }
}
